package com.siecom.bank;

import com.siecom.algorithm.sm.SMUtil;
import com.siecom.tool.ByteTool;
import com.siecom.tool.StringUtil;

public class SMEncrypt {
	/**
	 * 国密加密流程
	 */
	private byte[] masterKey;
	private byte[] workingKey;
	private String card_no;

	/**
	 * 设置主密钥
	 *
	 * @param masterKey
	 * @return
	 */
	public SMEncrypt setMasterKey(byte[] masterKey) {

		this.masterKey = masterKey;
		return this;
	}

	/**
	 * 工作密钥
	 *
	 * @param workingKey
	 * @return
	 */
	public SMEncrypt setWorkingKey(byte[] workingKey) {

		this.workingKey = workingKey;
		return this;
	}

	/**
	 * 卡号
	 *
	 * @param card_no
	 * @return
	 */
	public SMEncrypt setCardNo(String card_no) {

		this.card_no = card_no;
		return this;
	}

	/**
	 * 模拟输入PIN
	 * @param PIN
	 * @return
	 */
	public String inputPIN(String PIN) {

		String pin_str = builtPINStr(PIN);
		String card_str = builtCardStr(card_no);

		String real_workingKey = SMUtil.SM4DecryptECB(ByteTool.byte2hex(workingKey), ByteTool.byte2hex(masterKey));

		byte[] ex = ByteTool.hexStr2Bytes(StringUtil.XOR(pin_str, card_str));

		return  SMUtil.SM4EncryptECB(ByteTool.byte2hex(ex),real_workingKey);

	}



	/**
	 * 生成PIN的加密串
	 *
	 * @param PIN
	 * @return
	 */
	private static String builtPINStr(String PIN) {

		int length = PIN.length();
		String len = String.valueOf(length);
		len = (len.length() == 1) ? ("0" + len) : len;
		StringBuffer sb = new StringBuffer();
		sb.append(len);
		sb.append(PIN);
		for (; sb.length() < 32;) {
			sb.append("F");

		}
		System.out.println("pin:" + sb);
		return sb.toString();

	}

	/**
	 * 生成卡号的加密串
	 * @param card_no
	 * @return
	 */
	private static String builtCardStr(String card_no) {
		StringBuffer card_buff = new StringBuffer(card_no);
		card_buff = card_buff.reverse();
		card_buff = new StringBuffer(card_buff.substring(1, 13)).reverse();
		return StringUtil.padding(card_buff.toString(),"left","0",32);

	}
	/**
	 * 解密加密串
	 * @param ciphertext
	 * @return
	 */
	public String decrypt(String ciphertext) {

		String real_workingKey = SMUtil.SM4DecryptECB(ByteTool.byte2hex(workingKey), ByteTool.byte2hex(masterKey));

		String src = SMUtil.SM4DecryptECB(ciphertext,real_workingKey);
		String card_str = builtCardStr(card_no);
		byte[] tmp =  ByteTool.hexStr2Bytes(StringUtil.XOR(src, card_str));
		String str = ByteTool.byte2hex(tmp);
		System.err.println("str:"+str);
		int length = Integer.valueOf(str.substring(0, 2));
		String pin = str.substring(2, length + 2);
		return pin;
	}
}
